//
//  Skus.swift
//  APPCore
//
//  Created by raymond Peng on 2018/8/7.
//  Copyright © 2018 TanBaYe. All rights reserved.
//

import Foundation
import Domain

struct GoodsSku: Decodable {
    let sort: Int?
    let skuAttr: String?
    let skuId: String?
    let goodsweight: Int?
    let stocknum: Int?       // 商品库存数量
    let buyNum: Int?
    let isDefault: Bool?
    let expressGroups: String?  // 支持的快递: 逗号分隔的字符串
    let marketprice: String?    // 原价
    let maxCount: Int?       // 最大购买数限制
    let uniformprice: String?   // 代理价
    let group: String?          // 所属的互斥组
    let isSales: Bool?   // 是否是特价商品

    func getSkuTraitsArray() -> [GoodsSkuAttr] {
        guard let data = (skuAttr ?? "").data(using: .utf8) else { return [] }
        let arr: [GoodsSkuAttr]
        let decoder = JSONDecoder()
        do {
            arr = try decoder.decode([GoodsSkuAttr].self, from: data)
        } catch {
            arr = []
        }
        return arr
    }
}

extension GoodsSku: ISKUEntity {
    var id: String {
        return self.skuId ?? ""
    }

    var index: Int {
        return self.sort ?? -1
    }

    var skuAttrArray: [ISKUAttributesEntity] {
        return getSkuTraitsArray()
    }

    var weight: Int {
        return self.goodsweight ?? 0
    }

    var stockCount: Int {
        return self.stocknum ?? 0
    }

    var soldCount: Int {
        return self.buyNum ?? 0
    }

    var originalPrice: Double {
        return Double(self.uniformprice ?? "") ?? 0
    }

    var discountPrice: Double {
        return Double(self.marketprice ?? "") ?? 0
    }

}
